<template>
  <div class="app-container">
    <!--   功能区          -->
    <el-row :gutter="10" class="mb8">
      <div v-if="option">
        <!--  导出按钮    -->
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="exportToExcel"
            v-hasPermi="['uniquefees:stu_book:export']"
          >导出
          </el-button>
        </el-col>
        <!--  导入按钮    -->
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['uniquefees:stu_book:import']"
          >导入
          </el-button>
        </el-col>
        <!-- 发布账单 -->
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-s-promotion"
            size="mini"
            @click="handleRelease"
            v-hasPermi="['uniquefees:stu_book:release']"
          >发布
          </el-button>
        </el-col>
        <!-- 删除账单 -->
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-refresh-left"
            size="mini"
            @click="handleRevokeRelease"
            v-hasPermi="['uniquefees:stu_book:release']"
          >撤回发布
          </el-button>
        </el-col>
        <!--  显示列表控制    -->
        <el-col :span="1.5" style="float: right; margin-right: 5px">
          <el-dropdown :hide-on-click="false">
                <span class="el-dropdown-link">
                  <el-button icon="el-icon-setting" circle size="mini"/>
                </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="field in columns" :key="field.key">
                <el-checkbox :value="field.visible" @change="downChange(field.key)">{{ field.label }}</el-checkbox>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </div>

      <!--   开启编辑 TODO   -->
      <!--   刷新按钮   -->
      <el-col :span="1.5" style="float: right; margin-right: 5px">
        <el-button
          circle
          icon="el-icon-refresh"
          size="mini"
          @click="getList"
        />
      </el-col>
    </el-row>
    <div v-if="option">
      <el-table :data="studentData" v-loading="loading" style="width: 100%" border>
        <el-table-column type="index" width="50"/>
        <el-table-column prop="id" label="id" v-if="columns[0].visible"/>
        <el-table-column prop="stuNo" label="学号" v-if="columns[1].visible"/>
        <el-table-column prop="name" label="姓名" v-if="columns[2].visible"/>
        <el-table-column
          v-for="(course, index) in courses"
          :key="index"
          :prop="`course_${course.courseId}`"
          :label="course.courseBook">
        </el-table-column>
        <el-table-column prop="total" label="合计" v-if="columns[3].visible"/>
        <el-table-column prop="signature" label="签名" v-if="columns[4].visible"/>
      </el-table>
    </div>
    <el-empty description="请先添加选购项（课程与教材）！,若已经添加请尝试刷新！" v-if="!option"></el-empty>
    <!-- 账单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?listId=' + this.value"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {deptStuBook, releaseStu_book, revokeReleaseStu_book} from "@/api/uniquefees/stu_book";
import {getToken} from "@/utils/auth";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

export default {
  props: {
    value: [String, Object, Array]
  },
  name: "bill",
  dicts: [],
  data() {
    return {
      title:"",
      courses: [],
      studentData: [
        {id: 1, name: "曹天葵", course_0: 35.00, course_1: 33.50, total: 384.10, signature: ""},
        {id: 2, name: "邓庆伟", course_0: 35.00, course_1: 33.50, total: 373.40, signature: ""},
        // 其他学生信息省略...
      ],
      // 列信息
      columns: [
        {key: 0, prop: 'id', label: `id`, visible: false},
        {key: 1, prop: 'stuNo', label: `学号`, visible: false},
        {key: 2, prop: 'name', label: `姓名`, visible: true},
        {key: 3, prop: 'total', label: `合计`, visible: true},
        {key: 4, prop: 'signature', label: `签名`, visible: true},
      ],
      //教材导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/uniquefees/stu_book/importData"
      },
      // 是否显
      loading: false,
      option: false,
      // 查询参数
      queryParams: {
        scheduleId: null,
      },
      stuBooks: []
    };
  },
  computed: {},
  created() {
    this.queryParams.scheduleId = this.value
    this.getList();
  },
  methods: {
    /**
     * 导出excel
     */
    exportToExcel() {
      // 准备表头
      const headers = ["id", "姓名", ...this.courses.map(course => course.courseBook), "合计", "签名"];

      // 准备表格数据
      const data = this.studentData.map(student => {
        let row = {
          id: student.id,
          '姓名': student.name,
        };

        // 动态添加课程成绩
        this.courses.forEach(course => {
          row[course.courseBook] = student[`course_${course.courseId}`] || '';
        });

        // 添加其他字段
        row["合计"] = student.total;
        row["签名"] = student.signature;

        return row;
      });

      // 创建工作簿并添加数据
      const worksheet = XLSX.utils.json_to_sheet(data, { header: headers });
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      // 添加表头样式 TODO

      // 生成Excel文件并触发下载
      const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      saveAs(new Blob([wbout], { type: 'application/octet-stream' }), this.title+'.xlsx');
    },
    /** 发布按钮操作 */
    handleRelease() {
      this.loading = true;
      const data = {
        scheduleId: this.queryParams.scheduleId,
        stuBooks: this.stuBooks,
        courseBooks: this.courses,
        orderName: this.orderTitle,
      }
      this.$modal.confirm('发布账单需要花费较长时间，请耐心等待！').then(function () {
        return releaseStu_book(data)
      }).then(() => {
        this.loading = false;
        this.$modal.msgSuccess("已发布账单,前往订单系统查看！");
      }).catch(() => {
        this.loading = false;
      });

    },
    /** 撤回发布发布按钮操作 */
    handleRevokeRelease() {
      this.loading = true;
      const data = {
        scheduleId: this.queryParams.scheduleId,
      }
      this.$modal.confirm('撤回发布，会删除所有账单，请慎重操作！').then(function () {
        return revokeReleaseStu_book(data)
      }).then(() => {
        this.loading = false;
        this.$modal.msgSuccess("已撤回账单！");
      }).catch(() => {
        this.loading = false;
      });
    },
    /**
     * 查询缴费学生
     */
    getList() {
      this.loading = true;
      deptStuBook(this.queryParams).then(response => {
        this.courses = response.data.courseBooks || [];
        this.title = response.data.title;
        if (response.data.courseBooks.length > 0) {
          this.option = true;
        }
        this.totalPrice = response.data.totalPrice || 0;
        this.orderTitle = response.data.title;
        this.stuBooks = response.data.courseStu;
        this.initDate(response.data.courseStu);
        this.loading = false;
      });
    },
    /**
     * 格式化数据结构
     * @param date
     */
    initDate(date) {
      const emptyArray = [];
      date.forEach(stu => {
        let item = {
          id: stu.studentId,
          name: stu.studentName,
          stuNo: stu.stuNo,
          total: (stu.totalPrice / 100).toFixed(2)
        }
        stu.courses.forEach(course => {
          let price = ""
          if (course.subscribe) {
            price = (course.price / 100).toFixed(2);
          }
          const courseId = `course_${course.courseId}`;
          const coursevo = {[courseId]: price}
          item = {...item, ...coursevo}
        })
        emptyArray.push(item);
      })
      this.studentData = emptyArray;
    },
    /**
     * 展示的列表
     * @param val
     */
    downChange(val) {
      const column = this.columns.find(col => col.key === val);
      if (column) {
        column.visible = !column.visible;
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "账单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('uniquefees/stu_book/importTemplate', {}, `bill_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }

  }
};
</script>
